package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDTO;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author GRS
 * @since 2024/4/19 下午7:49
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService
{
    @Resource
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDTO setmealDTO)
    {
        // 保存套餐的基本信息，操作setmeal，执行INSERT操作
        this.save(setmealDTO);

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes = setmealDishes
            .stream()
            .peek(item -> item.setSetmealId(setmealDTO.getId()))
            .toList();

        // 保存套餐的菜品的关联信息，操作setmeal_dish，执行INSERT操作
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐，同时需要删除套餐和菜品的关联数据
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids)
    {
        // 查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper
            .in(Setmeal::getId, ids)
            .eq(Setmeal::getStatus, 1);
        long count = this.count(wrapper);

        // 如果不能删除，抛出一个业务异常
        if (count > 0)
            throw new CustomException("套餐正在售卖中，不能删除");

        // 如果可以删除，先删除套餐表中的数据 ==> setmeal
        this.removeByIds(ids);

        // 删除关系表中的数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId, ids);

        setmealDishService.remove(queryWrapper);
    }
}